package com.nzw.config;

import com.nzw.plugins.PagePlugin;
import org.apache.ibatis.plugin.Interceptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;

/**
 * Created by op on 2017/11/3.
 */
@Configuration
@AutoConfigureAfter(DruidConfiguration.class)
public class MyBatisConfig {
    @Autowired
    private MybatisProperties properties;
    @Autowired
    private ResourceLoader resourceLoader = new DefaultResourceLoader();

    @Bean
    public SqlSessionFactoryBean getSqlSessionFactoryBean(DataSource dataSource) {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
       // Resource resource=this.resourceLoader.getResource(this.properties.getMapperLocations()[0]);
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            sqlSessionFactoryBean.setMapperLocations(resolver.getResources(this.properties.getMapperLocations()[0]));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //sqlSessionFactoryBean.setMapperLocations(new Resource[]{resource});
        sqlSessionFactoryBean.setConfigLocation(this.resourceLoader.getResource(this.properties.getConfigLocation()));
        sqlSessionFactoryBean.setPlugins(new Interceptor[]{new PagePlugin()});
        //sqlSessionFactoryBean.setTypeAliasesPackage(this.properties.getTypeAliasesPackage());
        //sqlSessionFactoryBean.setTypeHandlersPackage(this.properties.getTypeHandlersPackage());


        return sqlSessionFactoryBean;
    }
}
